package com.shuidouxing.filetransferassistant;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;

import com.example.myapplicationtest20220224.R;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mmkv.MMKV;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import es.dmoral.toasty.Toasty;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "test";

    //private String serverUrl = "http://10.10.6.189:8080";
    private String serverUrl = "http://192.168.1.4:8080";

    MMKV kv;

    private EditText editText;
    private  Button mBtnServerUrl;
    private Button mBtnDownload;
    private Button mBtnUpload;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        editText = findViewById(R.id.editTextTextPersonName);
        mBtnServerUrl = findViewById(R.id.btn_serverUrl);
        mBtnDownload = findViewById(R.id.btn_download);
        mBtnUpload = findViewById(R.id.btn_upload);

        mBtnServerUrl.setOnClickListener(this::UpdateServerUrl);
        mBtnDownload.setOnClickListener(this::downloadFile);
        mBtnUpload.setOnClickListener(this::selectPicsAndUpload);

        kv = MMKV.defaultMMKV();
        if (kv.contains("serverUrl"))
        {
            serverUrl = kv.decodeString("serverUrl");
        }
        editText.setText(serverUrl);
        kv.encode("serverUrl", serverUrl);
        Log.d(TAG, serverUrl);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        
        PermissionsUtils.getInstance().checkPermissions(this, permissions, new PermissionsUtils.PermissionsResult() {
            @Override
            public void passPermission() {
                //全部授权
                Log.d(TAG, "passPermission: 完全授权！");
            }

            @Override
            public void continuePermission() {
                //部分拒绝
                Toasty.warning(mContext, "读写权限被拒绝").show();
            }

            @Override
            public void refusePermission() {
                //不再授权
                Toasty.warning(mContext, "读写权限被拒绝").show();
            }
        });
    }
    
    private void UpdateServerUrl(View view){
        Toasty.info(this, "更新服务器地址！").show();

        serverUrl = String.valueOf(editText.getText());
        kv.encode("serverUrl", serverUrl);
        Log.d(TAG,"Update Server Url: " + serverUrl);
    }

    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    private void downloadFile(View view) {
        Toasty.warning(this, "开始下载！").show();


        OkGo.<String>get(serverUrl + "/getfile")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String data = response.body();
                        String[] fileList = data.split("\r\n");
                        for (int i = 0; i < fileList.length; i++) {
                            Log.d("test", "getfile success " + fileList[i]);

                            OkGo.<File>get(serverUrl + "/FileServer/uploads/" + fileList[i])
                                    .execute(new FileCallback(getDir(Environment.getExternalStorageDirectory() + "/a"), fileList[i]) {
                                        @Override
                                        public void onSuccess(Response<File> response) {
                                            File f = response.body();

                                            Log.d("test", "get success " + f.getPath());
                                            Toasty.success(mContext, "下载成功：" + f.getPath()).show();
                                        }
                                    });
                            Log.d("test", "okgo get file");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        Toasty.error(mContext, response.message()).show();
                    }
                });
    }

    private void selectPicsAndUpload(View view) {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        for (int i = 0; i < result.size(); i++) {
                            LocalMedia localMedia = result.get(i);
                            Log.d("test", localMedia.getPath());
                            Log.d("test", localMedia.getRealPath());

                            File f = new File(localMedia.getRealPath());
                            OkGo.<String>post(serverUrl + "/FileServer/fileupload")
                                    .params("file", f)
                                    .execute(new StringCallback() {
                                        @Override
                                        public void onSuccess(Response<String> response) {
                                            String data = response.body();
                                            Log.d("test", "post success " + data);
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            Log.d("test", "post error :" + response.getException().getMessage());
                                        }
                                    });
                            Log.d("test", "okgo post file" + f.getPath());
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private String getDir(String dir) {
        Log.d(TAG, "getDir: " + dir);
        File f = new File(dir);
        if (!f.exists()) {
            boolean r = f.mkdirs();
            Log.d(TAG, "getDir: 不存在创建" + r);
        }
        return dir;
    }
}